//
//  XRUpdateViewController.m
//  X-Touch2
//
//  作用：下载菜谱
//
//  Created by shengchao yang on 12-3-8.
//  Copyright (c) 2012年 foxhis. All rights reserved.
//

#import "XRUpdateViewController.h"
#import "FileManager.h"
#import "DownloadFromInternet.h"
#import "Singleton.h"
#import "Common.h"
#import "Imports2.h"
#import "NSString+Additions.h"

@interface XRUpdateViewController(Private)
-(void) startUpdate;
-(void) notifyMessage:(NSString *)message;
@end

@implementation XRUpdateViewController
@synthesize exceptionMessage;
@synthesize statusMessage;
@synthesize textView;
@synthesize lblStatus;
@synthesize lblTitle;
@synthesize switchDetail;
@synthesize activityIndecator;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
    }
    return self;
}
#pragma mark 多线程处理
-(void)startBackgroundJob
{
	NSAutoreleasePool *pool =[[NSAutoreleasePool alloc] init];
	[self startUpdate];
	[pool release];
}
//发送通知
-(void)notifyMessage:(NSString *)message{ 
    MyNSLog(@"message=%@", message);
    self.statusMessage = message;
    if (switchDetail.on && [self.exceptionMessage length] == 0) {
        self.exceptionMessage = message;
    }
    [self performSelectorOnMainThread:@selector(UpdateProgress:) withObject:nil waitUntilDone:YES];
}
//更新界面
- (void)UpdateProgress:(id)sender{
    lblStatus.text = self.statusMessage;
    //增加更新异常信息
    if ([self.exceptionMessage length]>0) {
        [textView setText:[NSString stringWithFormat:@"%@\r\n%@",textView.text, self.exceptionMessage]];
        [textView scrollRectToVisible:CGRectMake(0, textView.contentSize.height-5, textView.contentSize.width, 10) animated:YES];
        self.exceptionMessage=@"";
    }
}

-(void) startUpdate{
    [activityIndecator startAnimating];
    if (![DownloadFromInternet reportToCMS:AppSession.ipadUdid]) {
        MyNSLog(@"授权验证失败！");
        [self notifyMessage:@"授权验证失败！！！"];
        [activityIndecator stopAnimating];
    }else{
        [self notifyMessage:@"授权验证成功！开始更新数据库..."];
        [FileManager fileDelete:DBRealPath];//删除数据库文件
        [FileManager fileDelete:XRTranslateRealPath];//删除多语言翻译对照文件
//        [FileManager fileDelete:[DocumentPath stringByAppendingPathComponent:AppImgFolder]];//删除图片目录和文件
        [Common createTables];//建表、建库
        
        [self notifyMessage:@"数据库创建完毕！\r\n开始下载桌号..."];
        NSInteger tableCount = [Common downLoadPluTable];
        
        if (tableCount == 0) {
            self.exceptionMessage = @"\t桌号[0个]下载失败！";
            [self notifyMessage:@"\t桌号[0个]下载失败！"];    
            [activityIndecator stopAnimating];
            return;
        }
        [self notifyMessage:[NSString stringWithFormat:@"\t桌号[%d个]下载完毕！\r\n开始下载多语言翻译对照文件...",tableCount]];
        if (![Common downLoadImageFixedURL:DownloadUrlXRTranslate folderName:@"" imageName:XRTranslate]) {
            NSString *url = [NSString stringWithFormat:@"%@/%@/%@",AppSession.downloadUrl,DownloadUrlXRTranslate,XRTranslate];
            self.exceptionMessage = [NSString stringWithFormat:@"下载多语言翻译对照文件失败：%@",url];
            [self notifyMessage:@"多语言翻译对照文件下载失败！"];
        }else {
            [self notifyMessage:[NSString stringWithFormat:@"多语言翻译对照文件下载成功！"]];
        }
        
        [self notifyMessage:[NSString stringWithFormat:@"\t多语言翻译对照文件下载完毕！\r\n开始下载工号..."]];
        NSInteger empCount = [Common downLoadPluEmpno];
        
        [self notifyMessage:[NSString stringWithFormat:@"\t工号[%d个]下载完毕！\r\n开始下载烧法...",empCount]];
        NSMutableArray *pluSpecialSorts = [Common downLoadPluSpecialSort]; 
        [self notifyMessage:[NSString stringWithFormat:@"\t烧法类别数量：%d",[pluSpecialSorts count]]];
        for (int i=0; i<[pluSpecialSorts count]; i++) {
            PluSpecialSort *pss = (PluSpecialSort *)[pluSpecialSorts objectAtIndex:i];
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 下载烧法类别：[%@]%@...",(i+1),[pluSpecialSorts count],pss.pssCode,JsonField(pss.pssDescripts)]];
            [Common downLoadPluSpecialCode:pss.pssCode];   
            [self notifyMessage:[NSString stringWithFormat:@"\t烧法类别：[%@]%@ 下载完成!",pss.pssCode,JsonField(pss.pssDescripts)]];
        }
        
        [self notifyMessage:[NSString stringWithFormat:@"烧法下载完毕！\r\n开始下载菜本数据...",empCount]];
        NSMutableArray *pluBooks = [Common downLoadPluBook];
        [self notifyMessage:[NSString stringWithFormat:@"菜本数量：%d",[pluBooks count]]];
        for (int i=0;i<[pluBooks count];i++) {
            PluBook *plubook = (PluBook *)[pluBooks objectAtIndex:i];
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 开始下载菜本：[%@]%@ ...",(i+1),[pluBooks count],plubook.pbCode,JsonField(plubook.pbDescripts)]];
            
            if (![Common downLoadImageFixedURL:DownloadUrlPluBookImgs folderName:FolderPluBookImgs imageName:plubook.pbImage]){
                NSString *url = [NSString stringWithFormat:@"%@/%@/%@",AppSession.downloadUrl,DownloadUrlPluBookImgs,plubook.pbImage];
                self.exceptionMessage = [NSString stringWithFormat:@"下载菜本图片失败：%@",url];
                [self notifyMessage:[NSString stringWithFormat:@"菜本[%@]图片下载失败！",JsonField(plubook.pbDescripts)]];
            }else {
                [self notifyMessage:[NSString stringWithFormat:@"菜本[%@]图片：%@ 下载成功！",JsonField(plubook.pbDescripts),plubook.pbImage]];
            }
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 菜本：[%@]%@ 下载完成!",(i+1),[pluBooks count],plubook.pbCode,JsonField(plubook.pbDescripts)]];
        }
        
        
        
        [self notifyMessage:@"菜本数据下载完成！\r\n开始下载大类、小类和菜品明细..."];
        NSMutableArray *pluMenus = [Common downLoadPluMenu:@""];//下载大类的时候不能传入pbCode!!!
        [self notifyMessage:[NSString stringWithFormat:@"大类数量：%d",[pluMenus count]]];
        for (int j=0;j<[pluMenus count];j++) {
            PluMenu *plumenu = (PluMenu *)[pluMenus objectAtIndex:j];
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 开始下载大类：[%@]%@ ...",(j+1),[pluMenus count],plumenu.pmCode,JsonField(plumenu.pmDescripts)]];
            
            NSMutableArray *pluSorts = [Common downLoadPluSort:plumenu.pmCode];
            [self notifyMessage:[NSString stringWithFormat:@"\t小类数量：%d",[pluSorts count]]];
            for (int k=0;k<[pluSorts count];k++) {
                PluSort *plusort = (PluSort *)[pluSorts objectAtIndex:k];
                [self notifyMessage:[NSString stringWithFormat:@"\t%d/%d 下载小类：[%@]%@ ...",(k+1),[pluSorts count],plusort.psCode,JsonField(plusort.psDescripts)]];
                
                NSMutableArray *pluPlus = [Common downLoadPluPlu:plusort.psCode pluMenu:plumenu.pmCode];
                [self notifyMessage:[NSString stringWithFormat:@"\t\t菜品数量：%d",[pluPlus count]]];
                for (int l=0;l<[pluPlus count];l++) {
                    PluPlu *pluplu = (PluPlu *)[pluPlus objectAtIndex:l];
                    if ([pluplu.ppType isEqualToString:@"0"]) {//食品
                        [Common downLoadPluFood:pluplu.ppCode];
                    }else if([pluplu.ppType isEqualToString:@"1"]){//香烟
                        [Common downLoadPluCigarete:pluplu.ppCode];
                    }else if([pluplu.ppType isEqualToString:@"2"]){//酒水
                        [Common downLoadPluDrink:pluplu.ppCode];
                    }else if([pluplu.ppType isEqualToString:@"3"]){//套餐
                        [Common downLoadPluPkg:pluplu.ppCode];
                    }
                    
                    if ([pluplu.ppStatus isContainString:@"1"]) {
                        if (![Common downLoadImageFixedURL:DownloadUrlPluPluImgs folderName:FolderPluPluImgs imageName:pluplu.ppImage]) {
                            NSString *url = [NSString stringWithFormat:@"%@/%@/%@",AppSession.downloadUrl,DownloadUrlPluPluImgs,pluplu.ppImage];
                            self.exceptionMessage = [NSString stringWithFormat:@"下载菜品图片失败：%@",url];
                            [self notifyMessage:[NSString stringWithFormat:@"\t\t\t    菜品[%@]图片下载失败！",JsonField(pluplu.ppDescripts)]];
                        }else {
                            [self notifyMessage:[NSString stringWithFormat:@"\t\t\t    菜品[%@]图片：%@ 下载成功！",JsonField(pluplu.ppDescripts),pluplu.ppImage]];
                        }
                    }
                    
                    [self notifyMessage:[NSString stringWithFormat:@"\t\t\t%d/%d 菜品：[%@]%@ 下载完成!",(l+1),[pluPlus count],pluplu.ppCode,JsonField(pluplu.ppDescripts)]];
                }
                [self notifyMessage:[NSString stringWithFormat:@"\t%d/%d 小类：[%@]%@ 下载完成!",(k+1),[pluSorts count],plusort.psCode,JsonField(plusort.psDescripts)]];
            }
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 大类：[%@]%@ 下载完成!",(j+1),[pluMenus count],plumenu.pmCode,JsonField(plumenu.pmDescripts)]];
        }
        
        [self notifyMessage:@"菜谱下载完成！\r\n开始下载OEM图片..."];
        if (![Common downLoadImageFixedURL:DownloadUrlOEMimg folderName:FolderOEMImg imageName:@"oem.png"]) {
            NSString *url = [NSString stringWithFormat:@"%@/%@/oem.png",AppSession.downloadUrl,DownloadUrlOEMimg];
            self.exceptionMessage = [NSString stringWithFormat:@"下载OEM图片失败：%@",url];
            [self notifyMessage:@"OEM图片下载失败！"];
        }else {
            [self notifyMessage:[NSString stringWithFormat:@"OEM图片下载成功！"]];
        }
        
        //下载两类图片
        [self notifyMessage:[NSString stringWithFormat:@"开始下载HotelInfo图片...",empCount]];
        NSMutableArray *hotelInfoImages = [Common downLoadOtherImage:@"HotelInfo"];
        [self notifyMessage:[NSString stringWithFormat:@"HotelInfo图片：%d张",hotelInfoImages.count]];
        for (int i=0;i<[hotelInfoImages count];i++) {
            OtherImage *temp = (OtherImage *)[hotelInfoImages objectAtIndex:i];
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 开始下载图片：...",(i+1),hotelInfoImages.count]];
            NSString *url = [NSString stringWithFormat:@"%@/%@/%@",AppSession.downloadUrl,DownloadUrlHotelInfoImgs,temp.imageName];
            
            if (![Common downLoadImageFixedURL:DownloadUrlHotelInfoImgs folderName:FolderHotelInfoImgs imageName:temp.imageName]){
                self.exceptionMessage = [NSString stringWithFormat:@"下载HotelInfo图片失败：%@",url];
                [self notifyMessage:[NSString stringWithFormat:@"下载HotelInfo图片失败：%@",url]];
            }else {
                [self notifyMessage:[NSString stringWithFormat:@"HotelInfo图片下载成功！%@",url]];
            }
        }
        [self notifyMessage:[NSString stringWithFormat:@"开始下载About图片...",empCount]];
        NSMutableArray *aboutImages = [Common downLoadOtherImage:@"About"];
        [self notifyMessage:[NSString stringWithFormat:@"About图片：%d张",aboutImages.count]];
        for (int i=0;i<[aboutImages count];i++) {
            OtherImage *temp = (OtherImage *)[aboutImages objectAtIndex:i];
            [self notifyMessage:[NSString stringWithFormat:@"%d/%d 开始下载图片：...",(i+1),aboutImages.count]];
            NSString *url = [NSString stringWithFormat:@"%@/%@/%@",AppSession.downloadUrl,DownloadUrlAboutImgs,temp.imageName];
            
            if (![Common downLoadImageFixedURL:DownloadUrlAboutImgs folderName:FolderAboutImgs imageName:temp.imageName]){
                self.exceptionMessage = [NSString stringWithFormat:@"下载About图片失败：%@",url];
                [self notifyMessage:[NSString stringWithFormat:@"下载About图片失败：%@",url]];
            }else {
                [self notifyMessage:[NSString stringWithFormat:@"About图片下载成功！%@",url]];
            }
        }        
        
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"update_switch"];//关闭自动更新设置
        self.exceptionMessage = @"数据更新完成！请重启本应用！";
        [self notifyMessage:@"数据更新完成！请重启本应用！"];  
        [activityIndecator stopAnimating];
    }
    [activityIndecator stopAnimating];
}

#pragma mark - View lifecycle
- (void)viewDidLoad{
    lblTitle.text = [NSString stringWithFormat:@"[ udid = %@ ]",AppSession.ipadUdid];
    lblStatus.text = @"开始更新数据...";
    textView.text=@"开始更新数据...";
    [switchDetail setOn:NO];//默认显示详细信息
    [self performSelectorInBackground:@selector(startBackgroundJob) withObject:nil];//启动更新入口
    [super viewDidLoad];
}

- (void)viewDidUnload{
    [self setStatusMessage:nil];
    [self setTextView:nil];
    [self setExceptionMessage:nil];
    [self setLblStatus:nil];
    [self setLblTitle:nil];
    [self setSwitchDetail:nil];
    [self setActivityIndecator:nil];
    [super viewDidUnload];
}
- (void)dealloc {
    [textView release];
    [exceptionMessage release];
    [statusMessage release];
    [lblStatus release];
    [lblTitle release];
    [switchDetail release];
    [activityIndecator release];
    [super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{
    return (interfaceOrientation == UIInterfaceOrientationLandscapeRight || interfaceOrientation == UIInterfaceOrientationLandscapeLeft) ;
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
}
@end